package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.Md5Utils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {


    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/loginPage.do")
    public String loginPage() {

        return "login";

    }

    /**
     * JSR303 验证    用来验证controller 的入参格式的
     * @param loginUser
     * @param model
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) {

        // 1. 非空验证
        if (result.hasErrors()){ // 如果校验结果有异常
            String error = result.getAllErrors().get(0).getDefaultMessage();
            model.addAttribute("error",error);
            return "login";
        }

        // 2. 用户名是否存在
        User userDB = userMapper.selectByName(loginUser.getName());
        if (userDB == null) {
            model.addAttribute("error","用户名不存在");

            return "login";
        }
        //3. 密码错误
        String loginUserPassword = loginUser.getPassword();
        String password = userDB.getPassword();
        String salt = userDB.getSalt();

        // 加密用户输入的密码 + 数据库里的盐
        String md5String = Md5Utils.getMD5String(loginUserPassword  + salt);

        if (!md5String.equals(password)){
            model.addAttribute("error","密码错误");

            return "login";
        }

        // 加密 用户得到token令牌  把token令牌 存到浏览器的cookie里

        TokenUtils.responseTokenByCookie(userDB,response,30);  // 登录成功的标志  给浏览器返回令牌

        // 登录成功 把用户放到Redis

        redisTemplate.opsForValue().set(userDB.getName(), JSON.toJSONString(userDB),30, TimeUnit.MINUTES);
        //登录成功重定向到列表页的方法
        return "redirect:list.do";

    }

}
